package com.tlgen.doc.utils;

import java.io.*;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class FileUtils {

    /**
     * 读取文件内容
     *
     * @param file
     * @return
     */
    public static String readFile(File file) {
        StringBuilder text = new StringBuilder();
        String encoding = "utf-8";
        try (InputStreamReader read = new InputStreamReader(Files.newInputStream(file.toPath()), encoding);
             BufferedReader bufferedReader = new BufferedReader(read)) {
            //判断文件是否存在
            if (file.isFile() && file.exists()) {
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    text.append(lineTxt).append("\n");
                }
            } else {
                throw new RuntimeException("找不到指定的文件!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text.toString();
    }

    /**
     * 生成文件
     *
     * @param content
     */
    public static void createFile(String content) {
        String dir = System.getProperty("user.dir");
        String username = System.getProperty("user.name");
        String projectName = dir.substring(dir.lastIndexOf("\\") + 1);
        String directory = "C:\\Users\\" + username + "\\speed-doc\\";
        File folder = new File(directory);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String pathname = directory + projectName + ".apifox.json";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        System.out.println("speed-doc 接口文档生成路径: " + pathname + " 生成时间: " + format);
        File file = new File(pathname);
        try {
            PrintWriter printWriter = new PrintWriter(file);
            printWriter.println(content);
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 当前目录下的所有文件-不包括目录-递归方法
     *
     * @param fileList
     */
    public static void getAllFile(File file, List<File> fileList) {
        if (file.isDirectory()) {
            for (File listFile : Objects.requireNonNull(file.listFiles())) {
                getAllFile(listFile, fileList);
            }
        } else {
            fileList.add(file);
        }
    }

    /**
     * 当前目录下的所有文件-不包括目录-递归方法
     *
     * @param fileList
     */
    public static void getAllFile(List<File> fileList) {
        String localDirectory = System.getProperty("user.dir");
        File file = new File(localDirectory);
        if (file.isDirectory()) {
            for (File listFile : Objects.requireNonNull(file.listFiles())) {
                getAllFile(listFile, fileList);
            }
        } else {
            fileList.add(file);
        }
    }

}
